const Mock = require("mockjs");
const bodyParser = require("body-parser");

// Mock.setup({
//   timeout: '200 - 600'
// })
// console.log(Mock);

//导出的这个函数是用于webpack配置的devServer下的before属性(可以理解为拦截器)
module.exports = function (app) {
  //vue-cli的webpack环境变量,用于后端接口好了不使用拦截
  if (process.env.MOCK === "true") {
    // // parse application/x-www-form-urlencoded
    // app.use(bodyParser.urlencoded({ extended: false }))
    // parse application/json
    app.use(bodyParser.json())

    // 允许跨域
    app.all("*", function (req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Methods","PUT, GET, POST, DELETE, OPTIONS");
      // 此处根据前端请求携带的请求头进行配置
      res.header("Access-Control-Allow-Headers","X-Requested-With, Content-Type");
      // 例如：我们公司的请求头需要携带Authorization和Client-Type，此处就应该按照以下进行配置
      // res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Client-Type");
      next();
    });

    app.get("/userInfo/get", (req, res) => {
      res.json(
        Mock.mock({
          name: "@cname()",
          id: "@id()",
          "age|18-40": 0,
          email: "@email()",
          image: "@image('100x100', '#50B347', '#FFF', 'mock')",
          description: "@paragraph()",
        })
      );
    });

    app.post("/login", (req, res) => {
      console.log("111111111111111111111");
      if (req.body.usrname == "zs" && req.body.password == "123") {
        console.log("2222222222222222222222");
        res.json(
          Mock.mock({
            code: "200",
            msg: "成功！",
          })
        );
      } else {
        console.log("333333333333333333333333");
        res.json(
          Mock.mock({
            code: "500",
            msg: "失败！",
          })
        );
      }
    });
  }
};
